package com.cloudcc.mobile.util;

import java.io.File;

import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.widget.RemoteViews;

import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.entity.MyChatter;
import com.cloudcc.mobile.entity.comment.Comments;
import com.cloudcc.mobile.util.DialogUtils.OnDoClickListener;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

public class LoadingUtils {
	private Context context;
	private MyChatter chatter;
	private Comments comments;
	private int num;
	private static int len=0;
	private DefaultHttpClient httpClient;
	private NotificationManager manager;
	private Notification notif;
	private static String path=Tools.getImagePath("/CloudCC/FuJian/");
	public LoadingUtils(Context context,MyChatter chatter,int num){
		this.context=context;
		this.chatter=chatter;
		this.num=num;
	}
	public LoadingUtils(Context context,Comments comments,int num){
		this.context=context;
		this.comments=comments;
		this.num=num;
	}
	public void loadingCommnetFile(){
		if(comments==null){
			return;
		}
		String id=comments.commentsFile.getFileid();
		final String fileName=comments.commentsFile.getFilename();
		final String type=comments.commentsFile.getContentType();
		final HttpUtils http=new HttpUtils();
		httpClient=(DefaultHttpClient) http.getHttpClient();
		httpClient.addRequestInterceptor(null);
		final String fileUrl=UrlTools.url+UrlTools.wenjianurl+id+"&binding="+AppContext.binding;
		Tools.i("fileUrl", fileUrl);
		final String filePathName=path+"/"+fileName+"."+type;
		Tools.i("fileUrl", filePathName);
		final File file=new File(filePathName);
		if(file.exists()){
			DialogUtils dialog=new DialogUtils(context);
			dialog.showDialog(context, "下载文件", "你已经下载此文件，是否覆盖此文件");
			dialog.setOnDoClicktListener(new OnDoClickListener() {
				@Override
				public void confirm() {
					FileUtil.deleteFile(file);
					loadingFile(fileName, type, http, fileUrl, filePathName); 
				}
				@Override
				public void cancel() {
					
				}
			});
		}else{
			loadingFile(fileName, type, http, fileUrl, filePathName); 
		}
	}
	public void loadingFile(){
		if(chatter==null){
			return;
		}
		String id=chatter.feedFile.get(0).fileid;
		final String fileName=chatter.feedFile.get(0).filename;
		final String type=chatter.feedFile.get(0).contentType;
		final HttpUtils http = new HttpUtils();
		httpClient=(DefaultHttpClient)http.getHttpClient(); 
		httpClient.addRequestInterceptor(null);
		final String fileUrl=UrlTools.url+UrlTools.wenjianurl+id+"&binding="+AppContext.binding;
		Tools.i("fileUrl", fileUrl);
		final String filePathName=path+"/"+fileName+"."+type;
		Tools.i("fileUrl", filePathName);
		final File file=new File(filePathName);
		if(file.exists()){
			Tools.showInfo(context, "文件下载完成！"+fileName+"已经保存在/Cloudcc/Fujian/");
			/*DialogUtils dialog=new DialogUtils(context);
			dialog.showDialog(context, "下载文件", "你已经下载此文件，是否覆盖此文件");
			dialog.setOnDoClicktListener(new OnDoClickListener() {
				@Override
				public void confirm() {
					FileUtil.deleteFile(file);
					loadingFile(fileName, type, http, fileUrl, filePathName); 
				}

				@Override
				public void cancel() {
					
				}
			});*/
		}else{
			loadingFile(fileName, type, http, fileUrl, filePathName); 
		}
	}
	private void loadingFile(final String fileName, String type,
			HttpUtils http, String fileUrl, String filePathName) {
		notification(fileName+"."+type);
		@SuppressWarnings({ "rawtypes", "unused" })
		HttpHandler httphandler = 
		http.download(fileUrl, filePathName, true, // 如果目标文件存在，接着未完成的部分继续下载。
				false, // 如果从请求返回信息中获取到文件名，下载完成后自动重命名。
				new RequestCallBack<File>() { 
			@Override
			public void onSuccess(ResponseInfo<File> arg0) {
				Tools.showInfo(context,"文件下载完成！"+fileName+"已经保存在/Cloudcc/Fujian/");
			} 
			@Override
			public void onStart() {
				super.onStart();
				//				Tools.showInfo(context,"正在下载");
			}	
			@Override
			public void onLoading(long total, long current,
					boolean isUploading) {
				Message msg = new Message();  
				msg.what = num;  
				msg.obj = current; 
				Tools.i("loadhandler", "总大小："+total);
				Tools.i("loadhandler", "已经下载："+current);
				loadhandler.sendMessage(msg);  
				len=(int) (current*100/total);
				if(current == total){  
					loadhandler.sendEmptyMessage(-2);  
				}  
				super.onLoading(total, current, isUploading);

			}

			@Override
			public void onFailure(HttpException arg0, String arg1) {

			}
		});
	}
	/**
	 * 下载通知
	 */
	protected void notification(String filePathName) {
		Intent intent=new Intent(AppContext.OPEN_FILE);
		AppContext.filePath=path+"/"+filePathName;
		PendingIntent pIntent = PendingIntent.getBroadcast(context, 0, intent, 0);  
		manager = (NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);  
		notif = new Notification();  
		notif.icon = R.drawable.chatter_download;  
		notif.tickerText = "正在下载...";  
		notif.flags=Notification.FLAG_AUTO_CANCEL;
		//通知栏显示所用到的布局文件  
		notif.contentView = new RemoteViews(context.getPackageName(), R.layout.loading_notification);  
		notif.contentIntent = pIntent;  
		notif.contentView.setTextViewText(R.id.loadingName, "正在下载("+filePathName+")");  
//		notif.contentView.setOnClickPendingIntent(R.id.intentbtn, pIntent);
		manager.notify(num, notif);
	}

	private Handler loadhandler = new Handler(){  
		@Override  
		public void handleMessage(Message msg) {  
			super.handleMessage(msg);  
			if(msg.what==num){
				notif.contentView.setTextViewText(R.id.content_view_text1, len+"%");  
				notif.contentView.setProgressBar(R.id.content_view_progress, 100, len, false);  
				if(len==100){
					notif.contentView.setTextViewText(R.id.loadingName, "下载完成！"); 
				}
				manager.notify(num, notif);  
			}else if(msg.what==-2){
//				Tools.showInfo(context, "下载完成");
			}
		}  
	};  
}
